package com.zhugang.week13.hash;

import java.util.*;

/**
 * @program algorithms
 * @description: ThreeSum
 * @author: chanzhugang
 * @create: 2022/12/02 17:58
 */
public class ThreeSum {

    /**
     * 15、三数之和
     * https://leetcode.cn/problems/3sum/
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        /**
         * 先排序，难点是重复元素的去重判断
         */
        // nums[i] + nums[j] + nums[k] == 0  且 i != j != k
        Arrays.sort(nums);
        int n = nums.length;
        Map<Integer, Integer> cacheMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            cacheMap.put(nums[i], i);
        }

        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < n - 1; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                // 去重a： 1,1,3...
                continue;
            }
            for (int j = i + 1; j < n; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    // 去重b 1,2,2
                    continue;
                }
                int target = -1 * (nums[i] + nums[j]);
                if (!cacheMap.containsKey(target)) {
                    continue;
                }
                Integer k = cacheMap.get(target);
                if (k > j) {
                    // 避免重复
                    List<Integer> list = Arrays.asList(nums[i], nums[j], nums[k]);
                    result.add(list);
                }
            }
        }
        return result;
    }
}